from google.appengine.api import users
from google.appengine.ext import db

from common import redirect, respond
from models import Album, Picture
from django.conf import settings

from django.utils.translation import ugettext as _

def home(request):
    """
    future plans:
     - picture of the day instead of a randomly selected one.
     - smart dynamic background?
    """
    user = users.get_current_user()
    pic = Picture.random()

    return respond('home.html', {'menu_home': True,
                                 'pod': pic,
                                 'LANGUAGES': settings.LANGUAGES,
                                 'LANGUAGE_CODE': request.LANGUAGE_CODE,})

def about(request):
    return respond('about.html', {'menu_about': True,
                                  'LANGUAGE_CODE': request.LANGUAGE_CODE,})

def page_not_found(request):
    """
    django somehow failed to do it itself. so let's tell them explicitly.
    """
    return respond('404.html')

# see http://makeyjl.blogspot.com/2009/02/using-djangos-i18n-in-google-app-engine.html
# from django.views.i18n
from django import http
from django.utils.translation import check_for_language

def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the GET parameters.
    """
    lang_code = request.GET.get('language', None)
    next = request.GET.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = http.HttpResponseRedirect(next)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang_code
        else:
            response.set_cookie('django_language', lang_code)
    return response

def feeds(request):
    """
    everyone loves rss feed.
    """
    from datetime import datetime

    pics = Picture.all().order('-submitted_date').fetch(10)
    return respond('feeds.xml', { 'pics': pics, 'site_url': "http://%s" % request.get_host(), })
